import {
  menuTreeApi,
  merchantCommissionsListAllApi,
  paymentSettlementCostTypeListAllApi
} from '@/apis/payment'
import { systemDistrictListDistrictApi } from '@/apis/system'
import { tools } from '@/utils/tools'
import isNil from 'lodash-es/isNil'
import isNumber from 'lodash-es/isNumber'

export default function useApis() {
  async function getMenuTreeList(roleId?: number) {
    const { success, data } = await menuTreeApi({ roleId })
    return success ? data : []
  }

  /** 获取区域列表 */
  async function getDistrictListDistrictDicts() {
    const { success, data } = await systemDistrictListDistrictApi()
    return success ? data : []
  }

  /** 获取行政区域 下拉列表数据 */
  async function getDistrictOpts(level?: number) {
    const { success, data } = await systemDistrictListDistrictApi()

    if (success) {
      if (level && isNumber(level)) {
        const flatData = tools.treeToList(data, { children: 'child' })
        const filterData = flatData.filter((item) => !isNil(item.level) && item.level === level)
        const treeData = tools.listToTree(filterData, {
          id: 'districtCode',
          pid: 'parentCode',
          children: 'child'
        })

        return (treeData || []).map((item) => ({
          label: item.districtName,
          value: item.districtCode
        }))
      }
      return data
    }

    return []
  }

  /** 获取费用类型下拉字典 */
  async function getFeeTypeOpts() {
    const { success, data } = await paymentSettlementCostTypeListAllApi()
    return success ? tools.listToOptions(data, { label: 'costType', value: 'costTypeId' }) : []
  }

  /** 获取规则下拉字典 */
  async function getRuleListOpts() {
    const { success, data } = await merchantCommissionsListAllApi()
    return success ? tools.listToOptions(data, { label: 'ruleName', value: 'ruleId' }) : []
  }

  return {
    getFeeTypeOpts,
    getRuleListOpts,
    getMenuTreeList,
    getDistrictOpts,
    getDistrictListDistrictDicts
  }
}
